/**
 * Copyright (c) <2010>, <SUNNY GUPTA>
 * All rights reserved.

 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of the <ORGANIZATION> nor the
 *     names of its contributors may be used to endorse or promote products
 *     derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <SUNNY GUPTA> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.gwtp.investmentadvisor.client.gui.financialsecuritysearch;

import java.util.ArrayList;
import java.util.List;

//import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.event.dom.client.HasChangeHandlers;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.SuggestOracle.Request;
import com.google.gwt.user.client.ui.SuggestOracle.Response;
import com.google.gwt.user.client.ui.SuggestOracle.Suggestion;
import com.google.inject.Inject;
import com.gwtp.investmentadvisor.client.common.ServerQuerySuggestOracle.SearchServer;
import com.gwtp.investmentadvisor.client.common.ServerQuerySuggestOracle.ServerQueryCallback;
import com.gwtp.investmentadvisor.client.dispatch.DispatchCallback;
import com.gwtp.investmentadvisor.client.place.PlaceNameTokens;
import com.gwtp.investmentadvisor.shared.action.FinancialSecuritySearch;
import com.gwtp.investmentadvisor.shared.action.FinancialSecuritySearchResult;
import com.gwtp.investmentadvisor.shared.entities.FinancialSecurityView;
import com.gwtp.investmentadvisor.shared.event.FinancialSecuritySearchEvent;
import com.gwtp.investmentadvisor.shared.event.FinancialSecuritySearchEventHandler;
import com.gwtplatform.dispatch.client.DispatchAsync;
import com.gwtplatform.mvp.client.EventBus;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.NoGatekeeper;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.proxy.RevealRootContentEvent;

/**
 * @author Sunny Gupta
 *
 */
public class FinancialSecuritySearchBoxPresenter 
    extends Presenter<FinancialSecuritySearchBoxPresenter.Display, 
                FinancialSecuritySearchBoxPresenter.Proxy> implements SearchServer {

  private static final String DEFAULT_RESPONSE_STRING = "Not Found";
  
  // Cached Dispatcher
  private final DispatchAsync dispatcher;
  
  // Server request & callback
  Request request;
  private ServerQueryCallback serverCallback;

  /**
   * Interface for binding the View.
   * @author Sunny Gupta
   *
   */
  public interface Display extends com.gwtplatform.mvp.client.View {
    // The Search Text Field
    HasValue<String> getSearchText();
    // The Sender for Search Text Change Event
    HasChangeHandlers getSearchTextChangeSender();
    // TEST
    SuggestBox getSuggestBox();
    // Configure Search Server for SuggestOracle
    void configureSearchServer(SearchServer searchServer);
    void setDefaultResponse(Response defaultResponse);
  }

  /**
   * 
   * @author Sunny Gupta
   *
   */
  @ProxyCodeSplit
  // TODO: Think whether this access needs Gate Keeper
  @NoGatekeeper
  @NameToken(PlaceNameTokens.FinancialSecuritySearchBoxNameToken)
  public interface Proxy extends 
      com.gwtplatform.mvp.client.proxy.ProxyPlace<FinancialSecuritySearchBoxPresenter> {
  }
  
  @Inject
  public FinancialSecuritySearchBoxPresenter(final Display display, final Proxy proxy, 
      final EventBus eventBus, final DispatchAsync dispatcher) {
    super(eventBus, display, proxy);
    
    // Initialize dispatcher
    this.dispatcher = dispatcher;
    
    // Configure Search Server
    this.getView().configureSearchServer(this);
    
    // Do the binding
    bind();
  }

  /* (non-Javadoc)
   * @see net.customware.gwt.presenter.client.BasicPresenter#onBind()
   */
  @Override
  protected void onBind() {
    super.onBind();
    
    // Add Event Handlers
    
    /**
     * Handler for FinancialSecuritySearchEvent
     * We don't want to hard link event handling and rather follow standard pattern
     * It's just that response code also resides in the same presenter in this case
     */
    addRegisteredHandler(FinancialSecuritySearchEvent.TYPE, new FinancialSecuritySearchEventHandler() {
      @Override
      public void onFinancialSecuritySearchEventComplete(
          FinancialSecuritySearchEvent event) {
        // Display Result on View
        showSearchResults(event);
      }
    });
  }

  /**
   * @param event
   */
  private void showSearchResults(FinancialSecuritySearchEvent event) {
    // For response
    Response response = new Response();
    List<Suggestion> suggestions = new ArrayList<Suggestion>(); 
    
    List<FinancialSecurityView> results = event.getFinancialSecuritySearchResult().getSearchResult();
    
    // Check if empty
    if (results.size() == 0) {
      suggestions.add(getNotFoundSuggestion());
    } else {
      for (FinancialSecurityView view : results) {
        suggestions.add(getAsSuggestion(view));
      }
    }
    
    response.setSuggestions(suggestions);
    
    // TODO: Indicate to display that processing is complete
    
    // Send response to callback
    serverCallback.onServerResponseReady(this.request, response);
  }
  
  private Suggestion getNotFoundSuggestion() {
    Suggestion suggestion = new Suggestion() {
      
      @Override
      public String getReplacementString() {
        return DEFAULT_RESPONSE_STRING;
      }
      
      @Override
      public String getDisplayString() {
        return DEFAULT_RESPONSE_STRING;
      }
    };
    
    return suggestion;
  }

  /**
   * Uses anonymous inner class to define a local implementation for {@link Suggestion} interface and return.
   * values from {@link FinancialSecurityView}
   * @param view
   * @return
   */
  private Suggestion getAsSuggestion(final FinancialSecurityView view) {
    Suggestion suggestion = new Suggestion() {
      
      @Override
      public String getReplacementString() {
        return view.getTickerSymbol();
      }
      
      @Override
      public String getDisplayString() {
        return view.getName();
      }
    };
    
    return suggestion;
  }

  private void doSearch(FinancialSecuritySearch financialSecuritySearch) {
    // Log.info("Calling doSend");
    
    /**
     * Execute with cache, since this search result will hardly change with time
     * For example, the results for 'stan' will be a subset of 'sta', and this can be
     * leveraged to do a subset search on locally available results.
     */
    
    dispatcher.execute(financialSecuritySearch,
        new DispatchCallback<FinancialSecuritySearchResult>() {

      @Override
      public void callback(FinancialSecuritySearchResult result) {
        // Take the result from the server and notify client interested components
        fireEvent(new FinancialSecuritySearchEvent(result));
      }
    });
  }

  /* (non-Javadoc)
   * @see com.gwt.investmentadvisor.client.common.ServerQuerySuggestOracle.SearchServer#performServerQuery(com.google.gwt.user.client.ui.SuggestOracle.Request, com.gwt.investmentadvisor.client.common.ServerQuerySuggestOracle.ServerQueryCallback)
   */
  @Override
  public void performServerQuery(Request request,
      ServerQueryCallback serverCallback) {
    // TODO: Indicate to display that processing has started
    
    // Form financialSecuritySearch
    FinancialSecuritySearch financialSecuritySearch = new FinancialSecuritySearch(request.getQuery());
    
    // Associate request & callback
    this.request = request;
    this.serverCallback = serverCallback;
    
    // Call doSearch
    doSearch(financialSecuritySearch);
  }

  @Override
  protected void revealInParent() {
    RevealRootContentEvent.fire(this, this);    
  }
}
